import time

from selenium.webdriver import ActionChains
from selenium.webdriver.common.by import By

from libs.action import WebDriverAction
from libs.game import Game
from libs.image import ImageTool
from libs.log import Log
from libs.movement import Movement
from libs.task_helper import TaskHelper
from libs.trade_helper import TradeHelper
from libs.window import AdsWindow

if __name__ == "__main__":
    parser = TaskHelper.default_args_parser('TreeInit')
    args = parser.parse_args()
    task_helper = TaskHelper.from_args(args)

    user_id = args.user_id
    log = Log(user_id)

    try:
        driver = AdsWindow(user_id).open(False)
        game = Game(driver, user_id)
        action = WebDriverAction(driver, user_id=user_id)
        movement = Movement(driver)
        image_tool = ImageTool(driver)
        trade_helper = TradeHelper(driver, user_id)
        ac = ActionChains(driver)

        game.enter_game()

        tree_name = 'Whittlewood Tree'
        tree_index = None
        for _ in range(3):
            tree_index, tree_qty = game.get_backpack_index_and_qty(tree_name)
            if tree_qty < 50:
                trade_helper.goto_seed_store()
                trade_helper.open_seed_buy()
                trade_helper.buy_seed(tree_name, 50 - tree_qty)
                action.escape()
                game.get_backpack()
            else:
                break
        action.goto_spec()
        movement.keep_move_up(1.5)
        movement.keep_move_left(1)
        movement.keep_move_down(0.5)
        movement.keep_move_left(4)

        game.use_backpack_item(tree_index)
        start_x = 190 # T2
        # start_x = 270 # T1
        start_y = 645
        offset_x = 80
        offset_y = -48
        for loop_y in range(13):
            y = start_y + loop_y * offset_y
            for loop_x in range(4):
                x = start_x + loop_x * offset_x
                action.move_by_offset(x, y)
                time.sleep(1)
                action.click()
        action.escape()

        trade_helper.goto_sell_position()
        trade_helper.open_shop_sell()
        trade_helper.sell_item(tree_name, 111, price_delta=-1)
        action.escape()
    except Exception as e:
        raise e